<template>
  <div class="manage-approval">
    <a-row style="width: 100%; height: 100%">
      <a-col class="classification hide-scroller-bar">
        <a-tree
          v-model:selectedKeys="selectedKeys"
          :tree-data="treeData"
          block-node
          @select="selectedKeyChange"
        >
          <template #title="{ title }">
            <div class="text-ellipsis">{{ title }}</div>
          </template>
        </a-tree>
      </a-col>
      <a-col flex="1" style="width: 100%; height: 100%">
        <a-row
          v-if="isSuperAdmin"
          style="background: #fff; padding-right: 10px; padding-top: 5px"
        >
          <a-col :xs="xsLayout" :lg="lgLayout">
            <a-row class="header" type="flex" justify="end" align="middle">
              <a-col>
                <a-space>
                  <a-button @click="addNewCat"> 新建分组 </a-button>
                  <a-button @click="catSortVisible = true">分组排序</a-button>
                  <a-button type="primary" @click="setApproval()">
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    创建审批
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
        <a-row
          class="right-list hide-scroller-bar"
          ref="container"
          @scroll="handleScroll"
        >
          <a-col :xs="xsLayout" :lg="lgLayout" v-if="!loading">
            <a-row v-if="dataList.length || showCatAdd">
              <a-col :span="24" class="card" v-show="showCatAdd">
                <div class="card-title">
                  <a-input
                    ref="addInput"
                    placeholder="请输入分组标题"
                    style="width: 50%; margin-right: 10px"
                    v-model:value="newCatTitle"
                  />
                  <a-button
                    type="link"
                    @click="saveNewCate"
                    :disabled="!newCatTitle"
                  >
                    保存
                  </a-button>
                  <a-button type="link" danger @click="addCatCancel">
                    取消
                  </a-button>
                </div>
              </a-col>
              <a-col
                :span="24"
                class="card data"
                v-for="data of dataList"
                :key="data.id"
                :id="data.id"
              >
                <!-- 分类 -->
                <div class="card-title between">
                  <div class="flex align-middle">
                    <template v-if="data.edit">
                      <a-input
                        placeholder="请输入分组标题"
                        style="width: 300px"
                        v-model:value="editCatName"
                      />
                      <a-space style="margin-left: 10px">
                        <a-button
                          type="link"
                          @click="editCate(data)"
                          :disabled="!data.cat_name"
                        >
                          保存
                        </a-button>
                        <a-button
                          type="link"
                          danger
                          @click="editCateCancel(data)"
                        >
                          取消
                        </a-button>
                      </a-space>
                    </template>
                    <template v-else>
                      <span>{{ data.cat_name }}</span>
                      <a-tooltip v-if="isSuperAdmin">
                        <template #title>编辑分类</template>
                        <a-button
                          type="link"
                          class="ml-10"
                          @click="handleCatEdit(data)"
                        >
                          <template #icon>
                            <EditOutlined />
                          </template>
                        </a-button>
                      </a-tooltip>
                    </template>
                  </div>
                  <a-space>
                    <a-tooltip v-if="isSuperAdmin">
                      <template #title>
                        <span
                          v-if="data.approval_list && data.approval_list.length"
                        >
                          无法删除，请先删除组内的审批
                        </span>
                        <span v-else>删除分类</span>
                      </template>
                      <a-button
                        type="link"
                        danger
                        :disabled="
                          data.approval_list && data.approval_list.length > 0
                        "
                        @click="handleCatRemove(data)"
                      >
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>
                  </a-space>
                </div>
                <!-- 审批 -->
                <div
                  class="approval-content"
                  v-if="data.approval_list && data.approval_list.length"
                >
                  <draggable
                    v-model="data.approval_list"
                    :group="data.id"
                    item-key="id"
                    handle=".order-icon"
                    @end="approvalDragEnd(data.approval_list)"
                  >
                    <template #item="{ element: approval }">
                      <div class="approval-list">
                        <a-avatar :src="approval.icon" :size="48" />
                        <div class="approval-name">
                          <div class="text-black">
                            <span>{{ approval.name }}</span>
                            <a-tag
                              v-if="approval.from_third"
                              style="margin-left: 10px"
                            >
                              由{{ approval.from_third }}提供
                            </a-tag>
                          </div>
                          <div class="text-gray">{{ approval.desc }}</div>
                        </div>
                        <div class="user-type">
                          <span v-if="approval.from_third">
                            可在{{ approval.from_third }}应用中发起
                          </span>
                          <span v-else>
                            {{ getUserType(approval.start_user_type) }}
                          </span>
                        </div>
                        <a-space>
                          <a-tooltip>
                            <template #title>编辑审批</template>
                            <a-button
                              type="link"
                              @click="setApproval(approval.id)"
                            >
                              <template #icon>
                                <FormOutlined />
                              </template>
                            </a-button>
                          </a-tooltip>
                          <a-tooltip v-if="approval.status == 4">
                            <template #title> 启用审批 </template>
                            <a-button
                              type="link"
                              @click="changeApprovalStatus(approval)"
                            >
                              <template #icon>
                                <CheckCircleOutlined />
                              </template>
                            </a-button>
                          </a-tooltip>
                          <a-tooltip v-if="approval.status == 1">
                            <template #title> 禁用审批 </template>
                            <a-button
                              type="link"
                              danger
                              @click="changeApprovalStatus(approval)"
                              :disabled="!!approval.alias"
                            >
                              <template #icon>
                                <StopOutlined />
                              </template>
                            </a-button>
                          </a-tooltip>
                          <a-tooltip v-if="isSuperAdmin">
                            <template #title>删除审批</template>
                            <a-button
                              type="link"
                              danger
                              @click="removeApproval(approval)"
                              :disabled="!!approval.alias"
                            >
                              <template #icon>
                                <DeleteOutlined />
                              </template>
                            </a-button>
                          </a-tooltip>
                          <a-tooltip v-if="isSuperAdmin">
                            <template #title>拖拽排序</template>
                            <div class="order-icon">
                              <MenuOutlined />
                            </div>
                          </a-tooltip>
                        </a-space>
                      </div>
                    </template>
                  </draggable>
                </div>
              </a-col>
            </a-row>
            <a-empty v-else style="margin-top: 40px" />
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <cat-sort
      :visible="catSortVisible"
      :list="dataList"
      @cancel="catSortVisible = false"
      @success="catSortSuccess"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  nextTick,
  reactive,
  toRefs,
  ref,
  onMounted,
  onUnmounted,
} from "vue";
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  MenuOutlined,
  EditOutlined,
  StopOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import common from "../SetApproval/js/common";
import utils from "../../../common/utils/utils";
import draggable from "vuedraggable";
import CatSort from "./module/CatSort.vue";

const xsLayout = { span: 24, offset: 0 };
const lgLayout = { span: 24, offset: 0 };

export default defineComponent({
  name: "ApprovalManage",
  components: {
    PlusOutlined,
    FormOutlined,
    DeleteOutlined,
    MenuOutlined,
    EditOutlined,
    StopOutlined,
    CheckCircleOutlined,
    draggable,
    CatSort,
  },
  setup() {
    const state = reactive({
      dataList: [],
      loading: false,
      showCatAdd: false,
      addInput: null,
      newCatTitle: "",
      editCatName: "",
      catSortVisible: false,
      isSuperAdmin: false,
      treeData: [],
      selectedKeys: [],
    });

    const router = useRouter();

    // 分组排序成功
    const catSortSuccess = () => {
      state.catSortVisible = false;
      getList();
    };

    // 拖拽审批列表
    let timer = null;
    const approvalDragEnd = (list) => {
      console.log("-----------approvalDragEnd", list);
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      timer = setTimeout(() => {
        setApprovalOrder(list);
      }, 600);
    };

    const setApprovalOrder = (list) => {
      const params = {
        sort_arr: list.map((item, index) => ({
          id: item.id,
          sort: list.length - index,
        })),
        needMsg: true,
      };
      request
        .put("/work_approval", "/manage/approval/sort", params)
        .then((res) => {
          message.success(res.msg || "排序成功！");
        });
    };

    // 修改审批状态
    const changeApprovalStatus = (approval) => {
      request
        .put("/work_approval", "/manage/approval/status", {
          id: approval.id,
          status: approval.status == 1 ? 4 : 1,
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "操作成功！");
          getList();
        });
    };

    // 删除审批
    const removeApproval = (approval) => {
      utils.modalConfirm({
        content: `确认删除审批"${approval.name}"吗？`,
        onOk: () => {
          request
            .del("/work_approval", "/manage/approval", {
              id: approval.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getList();
            });
        },
      });
    };

    // 审批-谁可以发起这个审批
    const getUserType = (userType) => {
      const type = common.memberOptions.find((item) => item.value == userType);
      return type.label;
    };

    // 编辑分组
    const handleCatEdit = (current) => {
      state.editCatName = current.cat_name;
      current.edit = true;
    };
    const editCate = (current) => {
      const index = state.dataList.findIndex(
        (item) => item.cat_name == state.editCatName && item.id != current.id
      );
      if (index > -1) {
        message.error("分组名称重复！");
        return;
      }
      request
        .put("/work_approval", "/manage/category", {
          id: current.id,
          cat_name: state.editCatName,
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "保存成功！");
          getList();
        });
    };

    // 取消编辑
    const editCateCancel = (current) => {
      current.edit = false;
    };

    // 删除分组
    const handleCatRemove = (current) => {
      utils.modalConfirm({
        content: `确认删除分组"${current.cat_name}"吗？`,
        onOk: () => {
          request
            .del("/work_approval", "/manage/category", {
              id: current.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功！");
              getList();
            });
        },
      });
    };

    // 添加分组
    const addNewCat = () => {
      state.showCatAdd = true;
      nextTick(() => {
        state.addInput.focus();
      });
    };
    const saveNewCate = () => {
      request
        .post("/work_approval", "/manage/category", {
          cat_name: state.newCatTitle,
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "添加成功！");
          addCatCancel();
          getList();
        });
    };
    const addCatCancel = () => {
      state.showCatAdd = false;
      state.newCatTitle = "";
    };

    // 创建、编辑审批
    const setApproval = (id) => {
      let query = {};
      if (id) {
        query = { id };
      } else {
        query = { type: "add" };
      }
      router.push({
        name: "SetApproval",
        query,
      });
    };

    const getList = (init = false) => {
      if (init) {
        state.loading = true;
      }
      request
        .get("/work_approval", "/manage/category", {
          withApproval: 1,
        })
        .then((res) => {
          state.dataList = res.list;
          state.treeData = res.list.map((item) => {
            return {
              title: item.cat_name,
              key: item.id,
            };
          });
          if (!selecteId.value.length) {
            state.selectedKeys = [state.treeData[0].key];
          }
          state.isSuperAdmin = res.isSuperAdmin;
        })
        .finally(() => {
          state.loading = false;
        });
    };
    const selecteId = ref([]);
    const selectedKeyChange = (e) => {
      if (!e.length) {
        state.selectedKeys = selecteId.value;
        return;
      }
      selecteId.value = e;
      scrollToAnchor(e[0]);
    };

    // 滚动到指定位置
    const scrollToAnchor = (id) => {
      const element = document.getElementById(id);
      if (element) {
        element.scrollIntoView({ behavior: "smooth" });
      }
    };

    const container = ref(null);

    // 滚动监听
    const handleScroll = () => {
      const containerEl = container.value.$el;
      const scrollTop = containerEl.scrollTop + 20;

      let nearestItem = null;
      let minDistance = Infinity;

      state.dataList.forEach((item) => {
        const itemEl = document.getElementById(`${item.id}`);
        if (!itemEl) return;

        const distance = scrollTop - itemEl.offsetTop;
        if (distance >= 0 && distance < minDistance) {
          minDistance = distance;
          nearestItem = item.id;
        }
      });

      if (nearestItem) {
        state.selectedKeys = [nearestItem];
      }
    };

    const init = () => {
      getList(true);
    };
    init();

    return {
      xsLayout,
      lgLayout,
      ...toRefs(state),
      addNewCat,
      saveNewCate,
      addCatCancel,
      setApproval,
      getUserType,
      editCate,
      editCateCancel,
      handleCatEdit,
      handleCatRemove,
      approvalDragEnd,
      catSortSuccess,
      changeApprovalStatus,
      removeApproval,
      scrollToAnchor,
      selectedKeyChange,
      handleScroll,
      container,
    };
  },
});
</script>
<style lang="less" scoped>
.manage-approval {
  width: 100%;
  height: 100%;
  .header {
    height: 50px;
  }

  .card {
    border: 1px solid #f1f1f1;
    border-radius: 8px;
    margin: 10px 0;
    .card-title {
      height: 60px;
      background: #f7f7f7;
      display: flex;
      align-items: center;
      padding: 20px 20px;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.8);
      font-weight: 500;
    }
    .approval-content {
      padding: 10px;
      .approval-list {
        display: flex;
        align-items: center;
        padding: 10px;
        user-select: none;
        .approval-name {
          flex: 1;
          margin: 0 20px;
          line-height: 24px;
          font-weight: 500;
        }
        .user-type {
          flex: 1;
        }
        .order-icon {
          cursor: all-scroll;
          margin-left: 10px;
          padding-right: 15px;
        }
      }
    }
  }

  .classification {
    background: #fff;
    margin-right: 8px;
    width: 200px;
    height: 100%;
    overflow: hidden auto;
    padding: 5px 10px 0px 10px;
    :deep(.ant-tree-switcher) {
      width: 0;
    }
    .text-ellipsis {
      width: 170px; /* 定义容器宽度 */
      white-space: nowrap; /* 确保文本在一行内显示 */
      overflow: hidden; /* 隐藏超出容器的内容 */
      text-overflow: ellipsis; /* 超出部分显示省略号 */
    }

    :deep(.ant-tree .ant-tree-node-content-wrapper) {
      line-height: 36px;
      padding-left: 10px;
    }
  }

  .right-list {
    widows: 100%;
    height: calc(100% - 55px);
    background: #fff;
    overflow: hidden auto;
    overflow-y: scroll;
  }
}
</style>
